/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pl.raflik.queryxml.lib;

import org.w3c.dom.Attr;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

/**
 *
 * @author raflik
 */
public class XMLNodePresenter {
    public static String getNodeName(Node node) {

        switch (node.getNodeType()) {
            case Node.ATTRIBUTE_NODE:
                Attr attr = (Attr) node;
                return attr.getName();
            case Node.CDATA_SECTION_NODE:
            case Node.COMMENT_NODE:
            case Node.PROCESSING_INSTRUCTION_NODE:
            case Node.TEXT_NODE:
                break;
            case Node.DOCUMENT_NODE:
                Document document = (Document) node;
                return getNodeName(document.getDocumentElement());
            case Node.ELEMENT_NODE:
                Element element = (Element) node;
                return element.getNodeName();
        }

        return "";
    }

    public static String getNodeValue(Node node) {
        StringBuilder sb = new StringBuilder();

        switch (node.getNodeType()) {
            case Node.ATTRIBUTE_NODE:
                Attr attr = (Attr) node;
                sb.append(attr.getValue());
                break;
            case Node.CDATA_SECTION_NODE:
            case Node.COMMENT_NODE:
            case Node.PROCESSING_INSTRUCTION_NODE:
            case Node.TEXT_NODE:
                CharacterData charData = (CharacterData) node;
                //String stringData = text.substringData(0, Math.min(text.getLength(), ITEM_MAX_LENGTH));
                String stringData = charData.substringData(0, charData.getLength());
                sb.append(stringData);
                break;
            case Node.DOCUMENT_NODE:
                Document document = (Document) node;
                return getNodeValue(document.getDocumentElement());
            case Node.ELEMENT_NODE:
                Element element = (Element) node;
                NamedNodeMap nodeMap = element.getAttributes();
                for (int i = 0; i < nodeMap.getLength(); i++) {
                    Node nodeAttr = nodeMap.item(0);
                    if (i > 0) {
                        sb.append(" ");
                    }
                    sb.append(nodeAttr.getNodeName() + "=" + nodeAttr.getNodeValue());
                }
                break;
        }

        return sb.toString();
    }

}
